package com.syezon.wifikey.safe;

import android.animation.ValueAnimator;
import android.arch.lifecycle.Observer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.blankj.utilcode.util.SpanUtils;
import com.syezon.wifikey.R;
import com.syezon.wifikey.analysis.AnalysisHelper;
import com.syezon.wifikey.analysis.event.EventEnum;
import com.syezon.wifikey.base.BaseActivity;
import com.syezon.wifikey.home.ResultHelper;
import com.syezon.wifikey.location.LocationInfo;
import com.syezon.wifikey.location.LocationService;
import com.syezon.wifikey.safe.adapter.CheckItemAdapter;
import com.syezon.wifikey.utils.StatusBarUtil;
import com.syezon.wifikey.view.RadarView;
import com.syezon.wifikey.view.expandablelayout.ExpandableLayout;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SafeCheckActivity extends BaseActivity {

    public static final String ARG_SSID = "ssid";
    public static final String ARG_SIGNAL = "signal";

    private static final int MSG_FINISH_CHECK_SAFE = 1;
    private static final int MSG_FINISH_LOCATION = 3;
    private static final int MSG_FINISH_ENHANCE = 2;

    private static final long CHECK_DUR = 4000;

    private static final long LOC_CHECK_DUR = 2000;

    @BindView(R.id.rl_top)
    RelativeLayout mRlTop;
    @BindView(R.id.ll_checking)
    LinearLayout mLlChecking;
    @BindView(R.id.ll_check_result)
    LinearLayout mLlCheckResult;
    @BindView(R.id.tv_check_state)
    TextView mTvCheckState;

    @BindView(R.id.radarView)
    RadarView mRadarView;
    @BindView(R.id.tv_safe_check_progress)
    TextView mTvSafeCheckProgress;

    @BindView(R.id.iv_location_check_indicator)
    ImageView mIvLocationIndicator;

    @BindView(R.id.expand_check)
    ExpandableLayout mExpandCheck;
    TextView mTvExpandCheckTitle;
    ImageView mIvSafeCheckIndicator;
    ImageView mIvExpandCheckProgress;
    RecyclerView mRvExpandItemList;


    @BindView(R.id.ll_location)
    LinearLayout mLlLocation;
    @BindView(R.id.expand_location)
    ExpandableLayout mExpandLocation;
    TextView mTvExpandLocationTitle;
    ImageView mIvLocationCheckIndicator;
    ImageView mIvExpandLocationProgress;
    TextView mTvExpandLocationContent;

    private ValueAnimator mCheckAnim;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_FINISH_CHECK_SAFE:
                    mTvSafeCheckProgress.setVisibility(View.GONE);
                    mIvLocationIndicator.setVisibility(View.VISIBLE);
                    mIvExpandCheckProgress.clearAnimation();
                    mIvExpandCheckProgress.setVisibility(View.GONE);
                    mExpandCheck.setLayoutAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            startLocation();
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                    mExpandCheck.show();
                    break;
                case MSG_FINISH_ENHANCE:
                    break;
                case MSG_FINISH_LOCATION:
                    mIvExpandLocationProgress.clearAnimation();
                    mIvExpandLocationProgress.setVisibility(View.GONE);
                    mExpandLocation.setLayoutAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            showResult();
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                    mExpandLocation.show();
                    break;
            }
        }
    };

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_safe_check;
    }

    @Override
    protected void initViewsAndEvents() {
        StatusBarUtil.setPaddingSmart(this, mRlTop);
        String ssid = getIntent().getStringExtra(ARG_SSID);
        if (TextUtils.isEmpty(ssid)) {
            finish();
            return;
        }
        mLlChecking.setVisibility(View.VISIBLE);
        mLlCheckResult.setVisibility(View.GONE);
        mTvExpandCheckTitle = mExpandCheck.findViewById(R.id.tv_title);
        mIvExpandCheckProgress = mExpandCheck.findViewById(R.id.iv_progress);
        mIvSafeCheckIndicator = mExpandCheck.findViewById(R.id.iv_indicator);
        mIvSafeCheckIndicator.setImageResource(R.drawable.ic_safe_check_indicator);
        mRvExpandItemList = mExpandCheck.findViewById(R.id.rv_list);
        mRvExpandItemList.setLayoutManager(new LinearLayoutManager(this));
        CheckItemAdapter checkItemAdapter = new CheckItemAdapter(this);
        checkItemAdapter.setData(getCheckList());
        mRvExpandItemList.setAdapter(checkItemAdapter);
//        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
//        dividerItemDecoration.setDrawable(mContext.getResources().getDrawable(R.drawable.app_list_diviver));
//        mRvExpandItemList.addItemDecoration(dividerItemDecoration);
//        mIvCheckAnim.startAnimation(AnimationUtils.loadAnimation(this, R.anim.anim_check_rotate));
        mLlLocation.setVisibility(View.GONE);
        mTvExpandLocationTitle = mExpandLocation.findViewById(R.id.tv_title);
        mIvLocationCheckIndicator = mExpandLocation.findViewById(R.id.iv_indicator);
        mIvLocationCheckIndicator.setImageResource(R.drawable.ic_location_check_indicator);
        mIvExpandLocationProgress = mExpandLocation.findViewById(R.id.iv_progress);
        mTvExpandLocationContent = mExpandLocation.findViewById(R.id.tv_content);
        AnalysisHelper.onEvent(EventEnum.SAFE_TEST_SHOW.eventId);
        mExpandLocation.setCanExpand(false);
        mExpandCheck.setCanExpand(false);
        startCheck();
        updateSafeCheckProgress(0);
    }

    private void startCheck() {
        mExpandCheck.startAnimation(AnimationUtils.loadAnimation(this, R.anim.anim_right_in));
        mTvExpandCheckTitle.setText("安全检测");
        mIvExpandCheckProgress.setVisibility(View.VISIBLE);
        mIvExpandCheckProgress.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate));
        mHandler.sendEmptyMessageDelayed(MSG_FINISH_CHECK_SAFE, CHECK_DUR);
        mCheckAnim = ValueAnimator.ofInt(0, 100).setDuration(CHECK_DUR);
        mCheckAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int currentValue = (int) animation.getAnimatedValue();
                updateSafeCheckProgress(currentValue);
            }
        });
        mRadarView.start();
        mCheckAnim.start();
    }

    private void updateSafeCheckProgress(int progress) {
        SpanUtils.with(mTvSafeCheckProgress)
                .append(progress + "")
                .setFontSize(19, true)
                .append("%")
                .setFontSize(10, true)
                .create();
    }


    private void startLocation() {
        mLlLocation.setVisibility(View.VISIBLE);
        mTvExpandLocationTitle.setText("WiFi位置");
        mExpandLocation.startAnimation(AnimationUtils.loadAnimation(this, R.anim.anim_right_in));
        mIvExpandLocationProgress.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate));
        LocationService.getInstance().getLocationLiveData().observe(this, new Observer<LocationInfo>() {
            @Override
            public void onChanged(@Nullable LocationInfo locationInfo) {
                mTvExpandLocationContent.setText(locationInfo.getAddress());
                mHandler.removeMessages(MSG_FINISH_LOCATION);
                mHandler.sendEmptyMessageDelayed(MSG_FINISH_LOCATION, LOC_CHECK_DUR);
            }
        });
        mHandler.removeMessages(MSG_FINISH_LOCATION);
        mHandler.sendEmptyMessageDelayed(MSG_FINISH_LOCATION, LOC_CHECK_DUR);
        LocationService.getInstance().getLocation();
    }

    @OnClick({R.id.iv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

    private void showResult() {
        mRadarView.stop();
        mLlChecking.setVisibility(View.GONE);
        mLlCheckResult.setVisibility(View.VISIBLE);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                ResultHelper.showWiFiSafeResult(mContext);
            }
        }, 2000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mRadarView.stop();
        if (mCheckAnim != null && mCheckAnim.isRunning()) {
            mCheckAnim.cancel();
        }
        mHandler.removeCallbacksAndMessages(null);
    }

    private List<String> getCheckList() {
        List<String> list = new ArrayList<>();
        list.add("检查网络是否被监听");
        list.add("检查是否为钓鱼WiFi");
        list.add("检查是否遭到DNS劫持");
        list.add("检查是否加密");
        list.add("检查Arp是否异常");
        list.add("检查是否存在SSL Strip攻击");
        return list;
    }
}
